package clark.model

import org.apache.log4j.Logger
import java.io.File
import java.sql.{Clob, SQLException, DriverManager, Connection,ResultSet}

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-3-2
 * Time: 下午3:50
 * @author Cui Gang
 * email:<a href="javascript:mailto">clarkhillm@gmail.com</a>
 */

object Tools {
    val url = "jdbc:derby:Note"
    val create = "jdbc:derby:Note;create=true"
    val driver = "org.apache.derby.jdbc.EmbeddedDriver"
    val user = "app"
    val password = "app"
    val logger = Logger.getLogger(this.getClass.getSimpleName)

    val connection: Connection = {
        try {
            val con = DriverManager.getConnection(url, user, password)
            logger.info("成功连接数据库")
            con
        } catch {
            case e: SQLException => {
                logger.error("连接数据库失败！=>" + e.toString)
                logger.info("创建新的数据库")
                DriverManager.getConnection(create, user, password)
            }
            case e: Exception => {
                logger.error("连接数据库失败！=>" + e.toString)
                connection
            }
        }
    }

    def clobHandler(clob: Clob): String = {
        val reader = clob.getCharacterStream
        val array = new Array[Char](clob.length.asInstanceOf[Int])
        reader.read(array)
        new String(array)
    }

    def drop {
        connection.createStatement.execute("drop table note")
    }

    def Rs(rs: ResultSet)(f: => Unit) {
        while (rs.next) {
            f
        }
    }

    def getPath: String = {
        val f = new File("temp.t")
        f.toURI.toString.split("temp")(0).split("file:")(1).substring(1)
    }
}